# coding: utf-8
import os
import pytest
from config.GlobalVar import G
from utils.OsUtil import mk_dir
from utils.ReportUtil import ReportUtil
from multiprocessing import Pool


def run_parallel(device_info, keywords=None):
    """
    测试执行主函数
    :param clear_cookie: 运行前是否先删除cookie文件，默认True删除
    :param keywords: 指定用例执行，可以为类名、测试方法名、测试文件名。默认None为全部执行。
        指定用例执行举例：keyword=["TestLoginPage.py", "TestPayInfoPage::test_add"]，
        则会执行TestLoginPage.py文件中的所有的测试方法，以及TestPayInfoPage类中的test_add方法
    :return:
    """
    # 根据设备名确定allure报告文件夹路径
    device_name = device_info["deviceName"]
    result_path = os.path.join(G.ALLURE_RESULT_PATH, device_name)
    report_path = os.path.join(G.ALLURE_REPORT_END_PATH, device_name)
    result_history_dir = os.path.join(G.ALLURE_RESULT_PATH, device_name, "history")
    report_history_dir = os.path.join(report_path, "history")
    # 启动pytest
    arguments = ["-v", "-s", f"--alluredir={result_path}", f"--cmdopt={device_info}"]
    if keywords:
        keywords = [k.replace("::", " and ") for k in keywords]
        arguments.append("-k")
        arguments.append(" or ".join(keywords))
    pytest.main(arguments)
    # 生成报告
    manager = ReportUtil()
    manager.generate_report(result_path, report_path, result_history_dir, report_history_dir)
    report_title_filepath = os.path.join(G.ALLURE_REPORT_END_PATH, device_name, "index.html")
    manager.set_windows_title(report_title_filepath)
    title_filepath = os.path.join(G.ALLURE_REPORT_END_PATH, device_name, "widgets", "summary.json")
    manager.set_report_name(title_filepath)


def pytest_main(device_infos, keywords=None):
    os.system('chcp 65001')  # 解决控制台乱码问题
    # 若文件夹不存在则初始化生成文件夹
    mk_dir(G.LOG_PATH)
    mk_dir(G.UPLOAD_FILEPATH)
    mk_dir(G.DOWNLOAD_FILEPATH)
    mk_dir(G.ALLURE_REPORT_PATH)
    mk_dir(G.ALLURE_RESULT_PATH)
    mk_dir(G.ALLURE_REPORT_END_PATH)
    mk_dir(G.SCREENSHOT_DIR)
    params = [(device_info, keywords) for device_info in device_infos]
    with Pool(len(device_infos)) as pool:
        pool.starmap(run_parallel, params)
        pool.close()
        pool.join()


if __name__ == '__main__':
    device_infos = [
        {"platformVersion": "9", "serverPort": 4725, "deviceName": "emulator-5554"},
        {"platformVersion": "14", "serverPort": 4726, "deviceName": "bea55cf7"}
    ]
    pytest_main(
        device_infos=device_infos,
        keywords=[
            "TestLoginPage",
        ]
    )
